interface Cate {
  id: number;
  name: string;
  parent: number;
  sort: number;
  children?: Cate[];
  // children: Cate[];
}

const toTree = (cates: Cate[]) => {
  return cateWalk(cates, 0);
};

function cateWalk(cates: Cate[], rootId: number) {
  let res: Cate[] = [];
  cates.forEach((item) => {
    if (item.parent == rootId) {
      res.push(item);

      // 儿子
      let children = cateWalk(cates, item.id);
      if (children.length > 0) {
        item.children = children;
      }
    }
  });

  return res;
}
const getLevel1 = (cates: Cate[]): any => {
  let level1 = cates
    .map((item) => {
      if (item.parent == 0) {
        return {
          id: item.id,
          name: item.name + ` ( ${item.id} )`,
        };
      }
    })
    .filter((item) => item);

  level1.unshift({
    id: 0,
    name: "无 ( 0 )",
  });

  return level1;
};

//
interface Doc {
  ebook_id: number;
  id: number;
  name: string;
  parent: number;
  sort: number;
  view_count: number;
  vote_count: number;
  children?: Doc[];
}
const toTreeDoc = (docs: Doc[]) => {
  return docNodeWalk(docs, 0);
};
function docNodeWalk(docs: Doc[], rootId: number) {
  let res: Doc[] = [];
  docs &&
    docs.forEach((item) => {
      if (item.parent == rootId) {
        res.push(item);

        // 看孩子
        let children = docNodeWalk(docs, item.id);
        if (children.length > 0) {
          item.children = children;
        }
      }
    });
  return res;
}
//
const getDocLevel1 = (docs: Doc[]): any => {
  let level1 = levelWalk(docs, 0);
  level1.unshift({
    id: 0,
    name: "无",
  });
  return level1;
};
function levelWalk(docs: Doc[], rootId: number) {
  let level1: any[] = [];
  docs &&
    docs.forEach((item) => {
      if (item.parent == rootId) {
        let temp: any = {
          id: item.id,
          name: item.name,
        };
        level1.push(temp);

        // 看孩子
        let children = levelWalk(docs, item.id);
        if (children.length > 0) {
          temp.children = children;
        }
      }
    });

  return level1;
}

export { toTree, getLevel1, toTreeDoc, getDocLevel1 };
